package org.testfire.realm.view.tags.json;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.context.FacesContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.apache.log4j.Logger;
import org.testfire.realm.util.S;
import org.testfire.realm.view.json.action.JsonAction;

/**
 * Created by IntelliJ IDEA.
 * User: granum
 * Date: Sep 3, 2007
 * Time: 8:50:49 PM
 */
public class JsonHandlerTag extends SimpleTagSupport
{

    Logger log = Logger.getLogger( JsonHandlerTag.class );

    public void doTag() throws JspException, IOException
    {
        super.doTag();

        ServletRequest request = ((PageContext)this.getJspContext()).getRequest();
        doJsonRequest( request );
    }

    public void doJsonRequest( ServletRequest request ) throws IOException
    {
        String actionEl = request.getParameter( "jsonActionEl" );
        String argString = request.getParameter( "jsonActionArgs" );
            String[] args = argString.split( "," );
        String[] actionArgs = parseArguments(args,  (HttpServletRequest)request );

        ExpressionFactory fact;
        ValueExpression ve;
        FacesContext context = FacesContext.getCurrentInstance();
        ELContext elContext = context.getELContext();
        fact = context.getApplication().getExpressionFactory();
        ve = fact.createValueExpression( elContext, String.format( "#{%1$s}", actionEl ), Object.class );
        JsonAction action = (JsonAction)ve.getValue( elContext );

        try
        {

            String result = action.perform( args, actionArgs );
            this.getJspContext().getOut().write( result );
            HttpServletResponse response = (HttpServletResponse)((PageContext)this.getJspContext()).getResponse();
            response.addHeader( "X-JSON", result );
        }
        catch ( Exception e )
        {
            PrintWriter p = new PrintWriter( this.getJspContext().getOut() );
            log.error( "", e );
            e.printStackTrace( p );
            p.flush();
        }
    }

    private String[] parseArguments( String[] args, HttpServletRequest request )
    {

        List<String> arguments = new ArrayList<String>();
        for ( String arg : args )
        {
            arg = arg.trim();
            if ( S.empty( arg ) )
            {
                continue;
            }
            if ( arg.charAt( 0 ) == ':' )
            {
                arg = request.getParameter( arg.substring( 1 ) );
            }
            arguments.add( arg );
        }
        return arguments.toArray( new String[arguments.size()] );


    }
}
